package com.huiquan.portal.controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.analysis.service.UserService;
import com.huiquan.foundation.constant.RoleID;
import com.huiquan.foundation.util.BusinessUtil;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.management.service.PageRoleService;
import com.huiquan.onlineTime.service.OnlineTimeRecordService;

/**
 * Description:
 *
 * @author
 * @Date 15/4/7
 * @since Ver 1.0
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private PageRoleService pageRoleService;
    @Autowired
    private OnlineTimeRecordService onlineTimeRecordService;

    private final Logger LOG = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping(value = "/login.htm")
    public ModelAndView login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        if (user != null) {
            redirect(user, resp);
            return null;
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("loginStatus", 1);
            if (BusinessUtil.isTestEnvironment()) {
                map.put("environmentFlag", "test");
            }
            return new ModelAndView("login", map);
        }
    }

    @RequestMapping(value = "/login_submit.htm")
    public void loginSubmit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        LOG.info("尝试登陆，username:{}", userName);
        if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
            resp.sendRedirect("/login.htm");
            return;
        }

        User user = userService.retrieveUser(userName.trim(), password.trim());

        if (user != null) {
            if (!user.getRole().equals(RoleID.ADMIN.getId())) {
                try {
                    onlineTimeRecordService.login(user, new Date());
                } catch (Exception e) {
                    LOG.error("loginSubmit set online time error, uid=" + user.getUserId());
                    e.printStackTrace();
                }
            }

            req.getSession().setAttribute("user", user);

            // 如果傅晴在每个月的4、5、6号三天登录则需要看到提醒信息
            setRemindFlag(req, user);

            LOG.info("login success, userName={}", new Object[]{userName});
            //先把页面保存入session
            pageRoleService.getAllPage(req, user);
            redirect(user, resp);
        } else {
            resp.sendRedirect("/login.htm");
        }
    }

    private void setRemindFlag(HttpServletRequest req, User user) {
        // 判断日期
        int dateNum = Calendar.getInstance().get(Calendar.DATE);
        boolean dateFlag = dateNum >= 4 && dateNum <= 6;

        // 判断登录人
        boolean userFlag = user.getUserId().equals(16L);

        if (dateFlag && userFlag) {
            req.getSession().setAttribute("remindFlag", "1");
        } else {
            req.getSession().setAttribute("remindFlag", "0");
        }
    }

    private void redirect(User user, HttpServletResponse resp) throws IOException {
        String redirect = onlineTimeRecordService.getRedirectURL(user);
        if (StringUtils.isNotBlank(redirect)) {
            resp.sendRedirect(redirect);
        } else {
            if (user.getUserId() == 16) {
                resp.sendRedirect("/vocab/element_list.htm?tabid=21_0");
            } else if (user.getUserId() == 2) {
                resp.sendRedirect("/analysis/sentence_list.htm?tabid=13_0");
            } else {
                resp.sendRedirect("/vocab/element_list.htm?tabid=21_0");
            }
        }
    }

    @ResponseBody
    @RequestMapping(value = "/remind_confirm.do")
    public ReturnData remindConfirm(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        // 设置提醒消息不打开
        req.getSession().setAttribute("remindFlag", "0");

        return ReturnUtil.success();
    }
}
